import pandas as pd
import numpyas np
from sklearnodelselection import train_test_split
fros kearnpreprcessng import Stndardaler
from sklearn.neighbors import KNeighborsClassifier
from skearnetrics import classification_report
from joblib inport dump
class ClassIfication(object):
    def __init__(self):
        self.df-pd.read_csv(dally.csv")
    def get_conditions(self):
    """
    分类前准备
    """
# 计算收益和风险比例
    df = self.df
    df['waxratio'] = df['max_close'] / df['the_close']
    df['minratfo'] = df['min_close'] / df['the_close']
#自动划分高低御值
high_return_threshold = df['maxratio'].quantile(0.4)#前4os定义为高收过
high_risk_threshold = df['nin_ratio'].quantile(e.4)#前4e%定义为高风

#生成分类标签
conditions = [
    (df['max_ratio')>=high_return_threshold)&(df['mim_ratio'] <= high_risk_threshold),
    (df['max_ratio']<=highreturn_threshold)&(df['mim_ratio'] > high_risk_threshold),
    (df['max_ratio']<high_return_threshold)&(df['mim_ratio'] > high_risk_threshold),
    (df['max_ratio']<high_return_threshold)&(df['mim_ratio'] <=  high_risk_threshold),
    ]

labels = [高收益高风险’，“高收益低风险”，“低收益低风险’，“低收益高风险”]
df['category']=np.select(conditions, labels, default=<未知)
#标签选择
features =df([
    'eps','total_revenue_ps','undist_profit_ps','gross_margin','fcff','fcfe','tangible_asset','bps','grossprofit_margin','npta'
    ])

#标签编码
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder
df ['catrgory_encoded'] = le.fit_transform(df['category'])
#数据标准化
scaler = StandardScaler()
x = scaler.fit_transform(features)
y = df['catrgory_encoded']
#划分训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=24)
return x train, x_test, y_train, y_test,le
def knn_utils(self, x_train, x_test, y_train, y_test):
    """
    Knn模型训练方法
    """
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(x_train, y_train)

#预测与评估

y_pred = knn.predict(x_test)
print(classification_report(y_test, target_names = le.c))

if __name == '__main__':
    ci = ClassIfication()
    x_train, x_test, y_train, y_test = ci.get_conditions()
    #ci.knn_utils(x_train, x_test, y_train, y_test,le)
    ci.svc_utils(X_train, X_test, y_train, y_test)